package Controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hr-system/Global"
	"hr-system/Model"
	response "hr-system/Response"
	"strconv"
)

type INewEmployeeController interface {
	RestController
	Update(c *gin.Context)
}

type NewEmployeeController struct {
	DB *gorm.DB
}

func NewNewEmployeeController() INewEmployeeController{
	db := Global.GetDB()
	return NewEmployeeController{DB: db}
}

func (n NewEmployeeController) PageList(c *gin.Context) {
	name, _ := c.GetPostForm("name")
	if name != ""{
		var selectEmployee Model.Employee

		// 查询
		result := n.DB.Model(&selectEmployee).Where("name=?", name).First(&selectEmployee).RowsAffected
		if result == 0 {
			response.Fail(c, "查无此员工", nil)
			return
		}
		response.Success(c, gin.H{"data": selectEmployee}, "查询成功")
		return
	}
	// 获取分页参数
	tempNum, _ := c.GetQuery("pagenum")
	tempSize, _ := c.GetQuery("pagesize")
	pageNum, _ := strconv.Atoi(tempNum)   // 当前页数
	pageSize, _ := strconv.Atoi(tempSize) // 页内个数
	if pageNum == 0 || pageSize == 0 {
		pageNum = 1
		pageSize = 10
	}
	// 分页
	var record []Model.Employee
	n.DB.Where("is_quit='否'").Order("id").Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&record)

	// 前端渲染分页也要知道总数
	var total int64
	n.DB.Model(Model.Employee{}).Count(&total)

	response.Success(c, gin.H{"data": record, "total": total}, "查询成功")
}

func (n NewEmployeeController) Create(c *gin.Context) {
	var requestEmployee Model.Employee
	_ = c.ShouldBind(&requestEmployee)
	updateEmployee := Model.Employee{}
	result := n.DB.Where("id=?",requestEmployee.Id).Find(&updateEmployee).RowsAffected
	if result != 0 {
		response.Fail(c, "该员工已存在", nil)
		return
	}
	err := n.DB.Create(&requestEmployee).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestEmployee}, "入职成功")
}

func (n NewEmployeeController) Update(c *gin.Context) {
	// 绑定body中参数（更新后的值）
	var requestEmployee Model.Employee
	_ = c.ShouldBind(&requestEmployee)
	// 获取path中的参数（要更新的值）
	EmployeeId, _ := c.GetPostForm("id")

	// 对比员工编号是否变化
	if requestEmployee.Id != EmployeeId {
		result := n.DB.Where("id=?",requestEmployee).First(&Model.Employee{}).RowsAffected
		if result != 0 {
			response.Fail(c, "员工已存在", nil)
			return
		}
	}
	// 更新
	var updateStore Model.Employee
	err := n.DB.Model(&updateStore).Where("id=?", EmployeeId).Updates(&requestEmployee).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestEmployee}, "修改成功")
}


